package com.hctforgreen.greenservice;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.HttpAuthHandler;
import android.webkit.WebSettings;
import android.webkit.WebSettings.TextSize;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hctforgreen.greenservice.ctr.DbController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.BookListEntity.BookEntity;
import com.hctforgreen.greenservice.model.MessagesListEntity.MessagesEntity;
import com.hctforgreen.greenservice.model.StudyEntity;
import com.hctforgreen.greenservice.utils.EntryCatalogUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;

/**
 * 终端培训：学习资料详情页
 * 
 * @author 390694
 * 2019-9-26
 */
public class TerminalStudyDetailActivity extends ParentActivity {
	private WebView webView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.rightScroll = false;
		setContentView(R.layout.activity_study_detail);
		initSkinLayout();

		initMessageContentWebView();

		initTitleButtonBar();
		initWindow();
	}

	private void initMessageContentWebView() {
		webView = (WebView) findViewById(R.id.wv_msg_contents);
		webView.setBackgroundColor(0); // 设置背景色
	}

	private void initTitleButtonBar() {
		final TextView titleTv = (TextView) findViewById(R.id.tv_title);
		titleTv.setText(getString(R.string.train_learning_materials));

		final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private void initWindow() {
		Intent intent = getIntent();
		if (intent.getBooleanExtra("isSpecial",false)){
			//从考试关联的资料跳转过来的
			String bookId = intent.getStringExtra("bookId");
			initMessageContentById(bookId);
		}else {
			StudyEntity entity = (StudyEntity) intent.getSerializableExtra(HctConstants.ON_ACTIVITY_KEY_STUDY_ENTITY);
			initMessageContentById(entity.id);
		}
	}

	private void renderMessageTitle(StudyEntity entity) {
		final TextView msgTitleTv = (TextView) findViewById(R.id.tv_msg_title);
		final TextView dateTv = (TextView) findViewById(R.id.tv_date);
		msgTitleTv.setText(entity.title);
		dateTv.setText(entity.date);
	}
/**
 * 资料详情
 */
	private void initMessageContentById(final String id) {
		final LinearLayout loadLyt = (LinearLayout) findViewById(R.id.lyt_default_load);
		final LinearLayout reloadLyt = (LinearLayout) findViewById(R.id.lyt_default_reload);
		final Button reloadBtn = (Button) findViewById(R.id.btn_default_reload);

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {

				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.GONE);

					hctResult = (HctResult) msg.obj;

					StudyEntity entity = (StudyEntity) hctResult.data;
					renderMessageTitle(entity);
					renderMessageContentUseWebView(entity);
					renderStudyExtra(entity);
					break;

				case HctConstants.STATUS_FAILD:
					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.VISIBLE);
					reloadBtn.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							initMessageContentById(id);
						}
					});
					break;
				}
			}

			/**
			 * 根据资料详情初始化关联的试题及视频
			 * 
			 * @param StudyEntity
			 *            entity
			 */
			private void renderStudyExtra(final StudyEntity entity) {
				if (entity == null) {
					return;
				}
				if (!TextUtils.isEmpty(entity.videoId)) {// 关联视频
					findViewById(R.id.lyt_study_video).setVisibility(
							View.VISIBLE);
					final TextView tvVideo = (TextView) findViewById(R.id.study_video);
					tvVideo.setText("   " + entity.videoName);
					findViewById(R.id.lyt_study_video).setOnClickListener(
							new OnClickListener() {

								@Override
								public void onClick(View v) {// 跳转到视频
									// videoId videoName
									Intent intent = new Intent(
											TerminalStudyDetailActivity.this,
											VideoPartsActivity.class);
									intent.putExtra("videoId", entity.videoId);
									intent.putExtra("videoName",
											entity.videoName);
									startActivity(intent);
								}
							});

				}

				if (!TextUtils.isEmpty(entity.examId)) {// 关联试卷
					findViewById(R.id.lyt_study_examine).setVisibility(
							View.VISIBLE);
					final TextView tvExam = (TextView) findViewById(R.id.study_exam);
					tvExam.setText("   " + entity.examName);
					findViewById(R.id.lyt_study_examine).setOnClickListener(
							new OnClickListener() {
								@Override
								public void onClick(View v) {// 跳转到试卷
									Intent intent = new Intent(
											TerminalStudyDetailActivity.this,
											TerminalPaperActivity.class);
									intent.putExtra(
											HctConstants.ON_ACTIVITY_KEY_PAPER_ID,
											entity.examId);
									startActivity(intent);
								}
							});

				}

				if (!TextUtils.isEmpty(entity.bookId)) {// 打开资料

					DbController dbController = new DbController(
							TerminalStudyDetailActivity.this);

					final BookEntity bookEntity = dbController
							.getBookEntity(entity.bookId);
					if (dbController.isExists(bookEntity)) {

						findViewById(R.id.lyt_study_book).setVisibility(
								View.VISIBLE);
						final TextView tvExam = (TextView) findViewById(R.id.study_book);
						tvExam.setText("   " + bookEntity.displayName);
						findViewById(R.id.lyt_study_book).setOnClickListener(
								new OnClickListener() {
									@Override
									public void onClick(View v) {// 跳转到资料
										EntryCatalogUtil catalogUtil = new EntryCatalogUtil();
										try {
											catalogUtil
													.startEntryCatalogActivity(
															TerminalStudyDetailActivity.this,
															bookEntity, true);
										} catch (Exception e) {
											e.printStackTrace();
										}
									}
								});
					}
				}
			}

			@SuppressLint("JavascriptInterface")
			private void renderMessageContentUseWebView(final StudyEntity entity) {

				// webView.setBackgroundColor(0); // 设置背景色
				// webView.getBackground().setAlpha(0); // 设置填充透明度 范围：0-255
				// 取消滚动条
				webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
				webView.setWebViewClient(mWebViewClient);

				webView.requestFocus(View.FOCUS_DOWN);
				webView.getSettings().setBlockNetworkImage(false);
				webView.getSettings().setSupportZoom(true);
				webView.getSettings().setDefaultTextEncodingName("UTF-8");
				webView.getSettings().setBuiltInZoomControls(true);

				webView.getSettings().setJavaScriptEnabled(true);
				webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(
						true);
				// webView.getSettings().setPluginsEnabled(true);
				webView.getSettings()
						.setPluginState(WebSettings.PluginState.ON);
				webView.getSettings().setSupportMultipleWindows(true);
				webView.getSettings().setTextSize(TextSize.NORMAL);

				webView.getSettings().setSaveFormData(false);
				webView.getSettings().setSavePassword(false);
				webView.getSettings().setUseWideViewPort(false);
				webView.setSaveEnabled(false);
				webView.clearCache(true);

				webView.addJavascriptInterface(new JavascriptInterface(
						TerminalStudyDetailActivity.this), "imagelistner");
				webView.loadDataWithBaseURL(null, entity.content, "text/html",
						"uft-8", null);
			}

		};

		loadLyt.setVisibility(View.VISIBLE);
		reloadLyt.setVisibility(View.GONE);
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(
							TerminalStudyDetailActivity.this);

					HctResult result = controller.getTerminalStudyDetail(id);
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();
	}

	private WebViewClient mWebViewClient = new WebViewClient() {
		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
		}

		@Override
		public void onReceivedHttpAuthRequest(WebView view,
				HttpAuthHandler handler, String host, String realm) {
			super.onReceivedHttpAuthRequest(view, handler, host, realm);
		}

		@Override
		public void onLoadResource(WebView view, String url) {
			super.onLoadResource(view, url);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			addImageClickListner();
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// if (view != null) {
			// view.loadUrl(url);
			// }
			Intent intent = new Intent();
			intent.setAction("android.intent.action.VIEW");
			Uri content_url = Uri.parse(url);
			intent.setData(content_url);
			startActivity(intent);
			return true;
		}
	};

	// 注入js函数监听
	private void addImageClickListner() {
		// 这段js函数的功能就是，遍历所有的img几点，并添加onclick函数，在还是执行的时候调用本地接口传递url过去
		webView.loadUrl("javascript:(function(){"
				+ "var objs = document.getElementsByTagName(\"img\"); "
				+ "for(var i=0;i<objs.length;i++)  " + "{"
				+ "    objs[i].onclick=function()  " + "    {  "
				+ "        window.imagelistner.openImage(this.src);  "
				+ "    }  " + "}" + "})()");
	}

	// js通信接口
	public class JavascriptInterface {

		private Context context;

		public JavascriptInterface(Context context) {
			this.context = context;
		}

		public void openImage(String img) {
			Intent intent = new Intent();
			intent.putExtra("image", img);
			intent.setClass(TerminalStudyDetailActivity.this,
					ShowMegaImageActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
	}
}
